import 'dart:io';

import 'package:flutter_tts/flutter_tts.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:ifly_speech_recognition/ifly_speech_recognition.dart';
import 'package:permission_handler/permission_handler.dart';

class SpeechService {
  final FlutterTts _flutterTts = FlutterTts();
  final FlutterSoundRecorder _recorder = FlutterSoundRecorder();
  bool _isListening = false;
  Timer? _silenceTimer;
  Function(double)? onSoundLevelChange;
  late SpeechRecognitionService _recognitionService;
  Function(String)? _onResultCallback;

  // 科大讯飞配置参数
  static const Map<String, String> XUNFEI_CONFIG = {
    "appId": "5a98b3f3",
    "apiKey": "f2fbdf6ddc3193612969c655863c3643",
    "apiSecret": "c7455f704e9dd1aa27c94b3bac2476e9"
  };

  Future<void> initialize() async {
    try {
      // 初始化讯飞语音识别服务
      _recognitionService = SpeechRecognitionService(
        appId: XUNFEI_CONFIG['appId']!,
        appKey: XUNFEI_CONFIG['apiKey']!,
        appSecret: XUNFEI_CONFIG['apiSecret']!,
      );

      await _recognitionService.initRecorder();

      // 设置语音识别回调
      _recognitionService.onRecordResult().listen(
        (message) {
          print('收到语音识别结果: $message');
          if (message.isNotEmpty) {
            _onResultCallback?.call(message);
          }
        },
        onError: (err) {
          print('语音识别错误: $err');
        },
        cancelOnError: false,
      );

      _recognitionService.onStopRecording().listen(
        (isAutomatic) {
          print('录音停止，是否自动停止: $isAutomatic');
          if (isAutomatic) {
            print('录音达到最大时长，自动停止');
          }
          _isListening = false;
        },
        onError: (err) {
          print('录音停止监听错误: $err');
        },
        cancelOnError: false,
      );

      // 初始化TTS
      await _flutterTts.setLanguage("zh-CN");
      await _flutterTts.setPitch(1.0);
      await _flutterTts.setSpeechRate(0.5);
      await _flutterTts.setVolume(1.0);

      _flutterTts.setStartHandler(() => print("开始播放"));
      _flutterTts.setCompletionHandler(() => print("播放完成"));
      _flutterTts.setErrorHandler((msg) => print("播放错误: $msg"));
    } catch (e) {
      print('初始化语音服务失败: $e');
      rethrow;
    }
  }

  // 添加权限检查方法
  Future<bool> _checkPermission() async {
    final micStatus = await Permission.microphone.request();
    final storageStatus = await Permission.storage.request();

    return micStatus.isGranted && storageStatus.isGranted;
  }

  Future<void> startListening(Function(String) onResult) async {
    if (!_isListening) {
      try {
        // 先检查权限
        if (!await _checkPermission()) {
          throw Exception('需要麦克风和存储权限才能进行录音');
        }

        _onResultCallback = onResult;
        _isListening = true;
        
        // 先开始语音识别
        _recognitionService.speechRecognition();
        
        // 等待一小段时间确保语音识别已经启动
        await Future.delayed(Duration(milliseconds: 200));
        
        // 开始录音
        await _recognitionService.startRecord();
        
        print('开始录音和识别');
      } catch (e) {
        _isListening = false;
        print('启动语音输入失败: $e');
        rethrow;
      }
    }
  }

  Future<void> stopListening() async {
    try {
      if (_isListening) {
        // 确保有足够的延迟让录音完成
        await Future.delayed(Duration(milliseconds: 200));
        await _recognitionService.stopRecord();
        _isListening = false;
        print('停止录音和识别');
      }
    } catch (e) {
      print('停止语音识别失败: $e');
      rethrow;
    }
  }

  Future<void> speak(String text) async {
    try {
      if (text.isNotEmpty) {
        await _flutterTts.stop();
        final result = await _flutterTts.speak(text);
        print("语音播放结果: $result");
      }
    } catch (e) {
      print('语音合成失败: $e');
      rethrow;
    }
  }

  Future<void> dispose() async {
    await _recorder.closeRecorder();
    await _flutterTts.stop();
  }

  bool get isListening => _isListening;

  // 分割长文本
  List<String> _splitText(String text, int maxLength) {
    List<String> segments = [];
    while (text.length > maxLength) {
      // 在标点符号处分割
      int splitIndex = text.substring(0, maxLength).lastIndexOf('。');
      if (splitIndex == -1) {
        splitIndex = text.substring(0, maxLength).lastIndexOf('，');
      }
      if (splitIndex == -1) {
        splitIndex = maxLength;
      }

      segments.add(text.substring(0, splitIndex + 1));
      text = text.substring(splitIndex + 1);
    }
    if (text.isNotEmpty) {
      segments.add(text);
    }
    return segments;
  }
}
